#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/26 21:22
# @Author  : WXY
# @File    : Mainwindow
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------
from py_gui.mainwindow_ui import Ui_MainWindow
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog
from PySide6.QtCore import  Slot,  Qt, QTimer
from GlobalExceptionHandler import GlobalExceptionHandler
from History import HistoryWindow  
from LoggerManager import logger_manager
import sys
import os
from utils import (setup_window_icon, setup_ffmpeg, show_info, show_warning, APPNAME,APP_TITLE,VERSION,
                   show_error, show_confirm_exit, SCROLLBARSTYLE, DISABLED_CONTROL_STYLE, setup_window_title,
                   format_timestamp_seconds, check_youtube_accessibility, check_network_connectivity)
from SystemMonitorWorker import SystemMonitorWorker
from SettingsManager import settings_manager
from YouTubeDownloadWorker import YouTubeDownloadWorker
from HistoryManager import history_manager
import threading
from i18n import i18n_manager, _, DISPLAY_TO_CODE_MAP, CODE_TO_INDEX_MAP,LANGUAGE_DISPLAY_NAMES, LANGUAGE_ORDER
from ProjectHelp import ProjectHelpWindow

# 尝试导入资源文件，如果失败则跳过
try:
    from py_gui import resouce_rc  # 导入资源文件

    print("✅ 资源文件导入成功")
except ImportError as e:
    print(f"⚠️ 资源文件导入失败: {e}")



class MainWindow(QMainWindow):
    def __init__(self, is_trial_mode=False):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # 窗体监控的消息设置为空
        self.ui.lbl_computer_msg.setText("")

        #self.setup_window( )
        # 设置窗口图标
        setup_window_icon(self)
        setup_window_title(self)

        self.setMinimumSize(800, 600)
        self.setMaximumSize(800, 600)

        # 初始化的时候，设置为0
        self.ui.progressBar.setValue(0)

        # 设置日志管理器的UI文本编辑器引用和信号连接
        if hasattr(self.ui, 'textEdit_debug'):
            logger_manager.set_ui_text_edit(self.ui.textEdit_debug)
            # 连接信号，确保跨线程UI更新安全
            logger_manager.ui_update_signal.connect(self._append_log_message)
            logger_manager.batch_update_signal.connect(self._append_batch_log_messages)
            logger_manager.info(_("messages.log_ui_enabled"), "main", show_in_ui=True)
        else:
            logger_manager.warning("⚠️ textEdit_debug控件未找到，日志将只输出到文件", "main")

        # 初始化项目帮助窗口
        self.help_dialog = None
        # 初始化历史记录窗口引用
        self.history_window = None

        # 下载工作线程引用
        self.download_worker = None
        self.is_downloading = False
        # 当前下载的URL，用于更新历史记录状态
        self.current_download_url = None
        # 工作线程引用
        self.worker_thread = None

        # 创建系统监控工作线程
        self.monitor_worker = SystemMonitorWorker()
        self.monitor_worker.monitor_updated.connect(self.update_system_monitor_display)
        self.monitor_worker.start()

        # 连接语言切换信号
        i18n_manager.language_changed.connect(self.on_language_changed)

        # 设置字符画文本
        self.setup_character_art_texts()

        # 连接按钮事件
        self.setup_connections()

        # 加载设置
        self.load_settings()

        # ✅ 添加初始化日志
        logger_manager.info(_("messages.main_window_init"), "main", show_in_ui=True)
        # 异步初始化历史记录管理器
        self.init_history_manager()

    def init_history_manager(self):
        """异步初始化历史记录管理器"""
        try:
            def init_history():
                try:
                    history_manager.initialize()
                    # # 如果没有历史记录，生成一些测试数据
                    # if len(history_manager.get_all_records()) == 0:
                    #     history_manager.generate_test_data()
                    logger_manager.info("✅ 历史记录管理器初始化完成", "main", show_in_ui=True)
                except Exception as e:
                    logger_manager.error(f"历史记录管理器初始化失败: {e}", "main", show_in_ui=True)

            # 在后台线程中初始化
            init_thread = threading.Thread(target=init_history, daemon=True)
            init_thread.start()

        except Exception as e:
            logger_manager.error(f"启动历史记录初始化线程失败: {e}", "main", show_in_ui=True)

    def start_download(self):
        """开始下载"""
        try:
            if self.is_downloading:
                # 如果正在下载，则取消下载
                if self.download_worker:
                    self.download_worker.cancel_download()
                    logger_manager.info("用户取消下载", "main", show_in_ui=True)
                return

            else:
                # 获取URL和下载路径
                url = self.ui.le_url.text().strip()
                download_path = self.ui.le_download_path.text().strip()

                if not url:
                    show_warning(self, "警告", "请输入YouTube视频URL")
                    self.ui.le_url.setFocus()
                    return

                if not download_path:
                    show_warning(self, "警告", "请选择下载路径")
                    self.ui.le_download_path.setFocus()  # 让路径文本框获取焦点
                    return

                # 检查下载路径是否存在
                if not os.path.exists(download_path):
                    show_warning(self, "警告", "下载路径不存在")
                    return

                # 保存当前下载的URL，用于后续更新历史记录
                self.current_download_url = url

                # 这里添加下载逻辑
                logger_manager.info(f"🚀 开始下载: {url}", "main", show_in_ui=True)
                logger_manager.info(f"📁 下载路径: {download_path}", "main", show_in_ui=True)

                self.ui.progressBar.setValue(0)
                self.is_downloading = True

                # 更新UI状态
                self.ui.btn_download.setText("取消下载")

                # 获取下载设置（从UI获取）
                # 从comboBox获取分辨率设置
                resolution_text = self.ui.comboBox.currentText()
                if resolution_text == "不限制":
                    resolution = None
                else:
                    resolution = resolution_text  # 360P, 720P, 1080P, 2K, 4K

                # 从comboBox_2获取格式设置（是/否转换为True/False）
                format_text = self.ui.comboBox_2.currentText()
                only_mp4 = True if format_text == "是" else False

                # 创建下载工作线程
                self.download_worker = YouTubeDownloadWorker(
                    url=url,
                    download_path=download_path,
                    resolution=resolution,
                    only_mp4=only_mp4
                )

                # 连接信号
                self.download_worker.progress_updated.connect(self.on_download_progress)
                self.download_worker.status_updated.connect(self.on_download_status)
                self.download_worker.download_finished.connect(self.on_download_finished)
                self.download_worker.log_message.connect(self.on_download_log)
                self.download_worker.video_info_extracted.connect(self.on_video_info_extracted)

                # 启动下载线程
                self.download_worker.start()
                # 添加到历史记录
                history_manager.add_record(
                    url=url,
                    title="下载中...",  # 初始标题，后续会更新
                    status="下载中",
                    download_path=download_path,
                    limit_resolution=resolution,
                    mp4_only=only_mp4
                )

        except Exception as e:
            logger_manager.error(f"开始下载时发生错误: {e}", "main")
            show_error(self, "错误", f"开始下载时发生错误: {e}")

    def cancel_download(self):
        """取消下载"""
        try:
            if self.download_worker and self.is_downloading:
                logger_manager.info("🛑 用户请求取消下载", "main", show_in_ui=True)
                self.download_worker.cancel_download()

                # 等待线程结束
                if self.download_worker.isRunning():
                    self.download_worker.quit()
                    self.download_worker.wait(3000)  # 等待最多3秒

                self.reset_download_ui()
                self.ui.progressBar.setValue(0)
                logger_manager.info("🛑 下载已取消", "main", show_in_ui=True)

        except Exception as e:
            logger_manager.error(f"取消下载失败: {e}", "main", show_in_ui=True)

    def setup_character_art_texts(self):
        """设置字符画文本，避免在UI文件中硬编码"""
        try:
            # 设置按钮文本
            self.ui.btn_download.setText(_("buttons.start_download"))
            self.ui.btn_clear_url.setText(_("buttons.clear_url"))

            # 设置其他按钮文本
            if hasattr(self.ui, 'pushButton'):  # 校验网络按钮
                self.ui.pushButton.setText(_("buttons.check_network"))

            if hasattr(self.ui, 'pushButton_2'):  # 历史记录按钮
                self.ui.pushButton_2.setText(_("buttons.history"))

            if hasattr(self.ui, 'btn_set_cookies'):  # 设置cookies按钮
                self.ui.btn_set_cookies.setText(_("buttons.set_cookies"))

            if hasattr(self.ui, 'btn_item_help'):  # 项目帮助按钮
                self.ui.btn_item_help.setText(_("buttons.btn_item_help"))

            if hasattr(self.ui, 'btn_select_path'):  # 选择路径
                self.ui.btn_select_path.setText(_("buttons.select_path"))
            # 设置标签文本

            if hasattr(self.ui, 'titleLabel'):
                self.ui.titleLabel.setText(_("app_title"))

            if hasattr(self.ui, 'lbl_set_text_2'):  # 视频/播放列表URL标签
                self.ui.lbl_set_text_2.setText(_("labels.lbl_set_text_2"))

            if hasattr(self.ui, 'lbl_set_text_3'):  # 限制最大分辨率标签
                self.ui.lbl_set_text_3.setText(_("labels.lbl_set_text_3"))

            if hasattr(self.ui, 'lbl_set_text_4'):  # 只下载MP4格式标签
                self.ui.lbl_set_text_4.setText(_("labels.lbl_set_text_4"))

            if hasattr(self.ui, 'lbl_set_text_5'):  # 请选择保存位置标签
                self.ui.lbl_set_text_5.setText(_("labels.lbl_set_text_5"))

            # 设置输入框占位符文本
            if hasattr(self.ui, 'le_url'):  # URL输入框
                self.ui.le_url.setPlaceholderText(_("labels.le_url"))

            if hasattr(self.ui, 'le_download_path'):  # 下载路径输入框
                self.ui.le_download_path.setPlaceholderText(_("labels.le_download_path"))

            # 设置textEdit_debug的滚动条样式
            if hasattr(self.ui, 'textEdit_debug'):
                self.ui.textEdit_debug.setStyleSheet(SCROLLBARSTYLE)
                #logger_manager.info("textEdit_debug滚动条样式设置完成", "main")
            #logger_manager.info("字符画文本设置完成", "main")

        except Exception as e:
            logger_manager.error(f"设置字符画文本失败: {e}", "main")
            # 如果设置失败，使用纯文本作为后备
            try:
                self.setWindowTitle(_("app_title"))
                self.ui.btn_download.setText(_("buttons.start_download", "开始下载"))
                self.ui.btn_clear_url.setText(_("buttons.clear_url", "清空"))

                if hasattr(self.ui, 'pushButton'):
                    self.ui.pushButton.setText(_("buttons.check_network", "校验网络"))
                if hasattr(self.ui, 'pushButton_2'):
                    self.ui.pushButton_2.setText(_("buttons.history", "历史记录"))
                if hasattr(self.ui, 'btn_start'):
                    self.ui.btn_start.setText(_("buttons.set_cookies", "设置cookies"))

                # 后备文本设置
                if hasattr(self.ui, 'lbl_set_text_2'):
                    self.ui.lbl_set_text_2.setText("视频/播放列表URL")
                if hasattr(self.ui, 'lbl_set_text_3'):
                    self.ui.lbl_set_text_3.setText("限制最大分辨率")
                if hasattr(self.ui, 'lbl_set_text_4'):
                    self.ui.lbl_set_text_4.setText("只下载MP4格式")
                if hasattr(self.ui, 'lbl_set_text_5'):
                    self.ui.lbl_set_text_5.setText("请选择保存位置")
                if hasattr(self.ui, 'le_url'):
                    self.ui.le_url.setPlaceholderText("请输入有效的YouTube视频链接")
                if hasattr(self.ui, 'le_download_path'):
                    self.ui.le_download_path.setPlaceholderText("请选择保存文件夹, 默认保存在当前文件夹下面")

                logger_manager.info("使用纯文本后备方案", "main")
            except Exception as fallback_error:
                logger_manager.error(f"后备文本设置也失败: {fallback_error}", "main")
    @Slot(int)
    def on_download_progress(self, progress):
        """处理下载进度更新"""
        self.ui.progressBar.setValue(progress)

    @Slot(str)
    def on_download_status(self, status):
        """处理下载状态更新"""
        logger_manager.info(f"📊 {status}", "download", show_in_ui=True)

    @Slot(str)
    def on_download_log(self, message):
        """处理下载日志消息"""
        logger_manager.info(message, "download", show_in_ui=True)

    @Slot(bool, str)
    def on_download_finished(self, success, message):
        """处理下载完成"""
        # 更新历史记录状态
        if self.current_download_url:
            if success:
                history_manager.update_record_status(self.current_download_url, _("status.download_complete"))
            else:
                history_manager.update_record_status(self.current_download_url, _("status.download_failed"))

        if success:
            logger_manager.info(f"{_('messages.download_complete')} {message}", "download", show_in_ui=True)
            show_info(self, _("status.download_complete"), message)
            self.ui.progressBar.setValue(100)
        else:
            logger_manager.error(f"{_('messages.download_failed')} {message}", "download", show_in_ui=True)
            show_error(self, _("status.download_failed"), message)

        self.reset_download_ui()

        # 清理工作线程
        if self.download_worker:
            self.download_worker.deleteLater()
            self.download_worker = None

    @Slot(str)
    def on_video_info_extracted(self, title):
        """处理视频信息提取完成"""
        try:
            # 更新历史记录中的标题
            if hasattr(self, 'current_download_url') and self.current_download_url:
                history_manager.update_record_title(self.current_download_url, title)
                logger_manager.info(f"历史记录标题已更新: {title}", "main")
        except Exception as e:
            logger_manager.error(f"更新历史记录标题失败: {e}", "main")

    def reset_download_ui(self):
        """重置下载UI状态"""
        self.ui.btn_download.setText(_("buttons.start_download"))
        self.is_downloading = False

    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            # 停止系统监控线程
            if hasattr(self, 'monitor_worker') and self.monitor_worker:
                self.monitor_worker.stop()

            # 停止其他工作线程
            if self.worker_thread and self.worker_thread.isRunning():
                self.worker_thread.quit()
                self.worker_thread.wait()

            # 保存历史记录到文件
            try:
                history_manager.save_to_file()
                logger_manager.info("历史记录已保存", "main")
            except Exception as e:
                logger_manager.error(f"保存历史记录失败: {e}", "main")

            logger_manager.info("主窗口正在关闭", "main")
            event.accept()

        except Exception as e:
            logger_manager.error(f"关闭窗口时发生错误: {e}", "main")
            event.accept()

    def setup_connections(self):
        """设置信号连接"""
        try:
            # 连接按钮点击事件
            self.ui.btn_download.clicked.connect(self.start_download)
            self.ui.btn_clear_url.clicked.connect(self.clear_url)
            self.ui.btn_select_path.clicked.connect(self.select_download_path)

            # 连接 comboBox 变化事件
            self.ui.comboBox.currentTextChanged.connect(self.save_resolution_setting)
            self.ui.comboBox_2.currentTextChanged.connect(self.save_mp4_setting)

            # 连接语言切换 comboBox 事件
            if hasattr(self.ui, 'languageComboBox'):
                self.ui.languageComboBox.currentTextChanged.connect(self.on_language_combo_changed)

            # 连接其他按钮事件, 校验网络
            if hasattr(self.ui, 'pushButton'):
                self.ui.pushButton.clicked.connect(self.check_network)

            if hasattr(self.ui, 'pushButton_2'):
                self.ui.pushButton_2.clicked.connect(self.show_history)
            # 设置cookies按钮事件
            if hasattr(self.ui, 'btn_set_cookies'):
                self.ui.btn_set_cookies.clicked.connect(self.set_cookies)

                    # 项目帮助按钮事件
            if hasattr(self.ui, 'btn_item_help'):
                self.ui.btn_item_help.clicked.connect(self.show_project_help)
            # 连接菜单事件（如果有的话）
            # self.ui.action_about.triggered.connect(self.show_about)
            # self.ui.action_help.triggered.connect(self.show_help)

            #logger_manager.info("信号连接设置完成", "main")

        except Exception as e:
            logger_manager.error(f"设置信号连接失败: {e}", "main")

    def show_project_help(self):
        """显示项目帮助窗口"""
        try:
            # 创建并显示项目帮助窗口
            self.project_help_window = ProjectHelpWindow(self)
            self.project_help_window.show()

            logger_manager.info("项目帮助窗口已打开", "main")

        except Exception as e:
            logger_manager.error(f"显示项目帮助窗口失败: {e}", "main")
            show_error(self, _("errors.help_dialog_failed", "显示帮助信息失败"), str(e))

    def save_resolution_setting(self, resolution_text):
        """保存分辨率设置"""
        try:
            # 获取当前设置
            last_input_path, last_output_path, debug_open, select_resolution, is_mp4, lange = settings_manager.get_main_info()

            # 保存新的分辨率设置
            settings_manager.save_main_info(
                last_input_path,
                last_output_path,
                debug_open,
                resolution_text,  # 新的分辨率设置
                is_mp4,
                lange
            )
            logger_manager.debug(f"分辨率设置已保存: {resolution_text}", "main")

        except Exception as e:
            logger_manager.error(f"保存分辨率设置失败: {e}", "main")

    def save_mp4_setting(self, mp4_text):
        """保存MP4格式设置"""
        try:
            # 获取当前设置
            last_input_path, last_output_path, debug_open, select_resolution, is_mp4, lange = settings_manager.get_main_info()

            # 转换文本为数字
            mp4_value = "1" if mp4_text == "是" else "0"

            # 保存新的MP4设置
            settings_manager.save_main_info(
                last_input_path,
                last_output_path,
                debug_open,
                select_resolution,
                mp4_value,  # 新的MP4设置
                lange
            )
            logger_manager.debug(f"MP4格式设置已保存: {mp4_text}", "main")

        except Exception as e:
            logger_manager.error(f"保存MP4格式设置失败: {e}", "main")

    def check_network(self):
        """校验网络连接"""
        try:
            logger_manager.info("🌐 开始校验网络连接", "main", show_in_ui=True)
            
            # 首先检查基本网络连通性
            network_result = check_network_connectivity()
            
            if not network_result['success']:
                show_error(self, "网络校验失败", network_result['message'])
                logger_manager.error(f"基本网络连通性检查失败: {network_result['message']}", "main")
                return
            
            # 检查YouTube的可访问性
            youtube_result = check_youtube_accessibility()
            
            if youtube_result['success']:
                message = f"{youtube_result['message']}\n\n✅ 可以正常下载YouTube视频"
                show_info(self, "网络校验成功", message)
                logger_manager.info(f"YouTube访问检查成功: {youtube_result['message']}", "main")
            else:
                message = f"{youtube_result['message']}\n\n⚠️ 可能无法正常下载YouTube视频\n建议检查网络设置或使用VPN"
                show_warning(self, "YouTube访问异常", message)
                logger_manager.warning(f"YouTube访问检查失败: {youtube_result['message']}", "main")

        except Exception as e:
            error_msg = f"网络校验过程中发生错误: {e}"
            logger_manager.error(error_msg, "main", show_in_ui=True)
            show_error(self, "错误", error_msg)

    def show_history(self):
        """显示历史记录"""
        try:
            logger_manager.info("⏳ 打开历史记录", "main", show_in_ui=True)
            
            # 检查历史记录窗口是否已存在且有效
            if self.history_window is not None and self.history_window.isVisible():
                # 如果窗口已存在且可见，将其调到最前
                self.history_window.raise_()
                self.history_window.activateWindow()
                logger_manager.info("✅ 历史记录窗口已调到最前", "main", show_in_ui=True)
            else:
                # 创建新的历史记录窗口
                self.history_window = HistoryWindow(self)
                # self.history_window.setWindowFlags(Qt.WindowType.Window)
                # self.history_window.setWindowFlags(Qt.WindowType.Window)
                self.history_window.show()
                logger_manager.info("✅ 历史记录窗口已打开", "main", show_in_ui=True)

        except Exception as e:
            logger_manager.error(f"打开历史记录失败: {e}", "main", show_in_ui=True)
            show_error(self, "错误", f"打开历史记录失败: {e}")

    def set_cookies(self):
        """设置cookies"""
        try:
            logger_manager.info("🍪 打开cookies设置", "main", show_in_ui=True)
            
            # 导入SetCookies窗口
            from SetCookies import SetCookiesWindow
            
            # 创建并显示cookies设置窗口
            self.cookies_window = SetCookiesWindow(self)
            self.cookies_window.show()
            
            logger_manager.info("✅ Cookies设置窗口已打开", "main", show_in_ui=True)

        except Exception as e:
            logger_manager.error(f"打开cookies设置失败: {e}", "main", show_in_ui=True)
            show_error(self, "错误", f"打开cookies设置失败: {e}")

    def load_settings(self):
        """加载用户设置"""
        try:
            # 从设置管理器加载设置
            last_input_path, last_output_path, debug_open, select_resolution, is_mp4, lange = \
                settings_manager.get_main_info()

            # 设置下载路径
            if last_output_path:
                self.ui.le_download_path.setText(last_output_path)

            # 设置分辨率选择
            if select_resolution:
                # 查找并设置 comboBox 的值
                index = self.ui.comboBox.findText(select_resolution)
                if index >= 0:
                    self.ui.comboBox.setCurrentIndex(index)

            # 设置MP4格式选择
            if is_mp4:
                # is_mp4 是字符串 "0" 或 "1"
                mp4_text = "是" if is_mp4 == "1" else "否"
                index = self.ui.comboBox_2.findText(mp4_text)
                if index >= 0:
                    self.ui.comboBox_2.setCurrentIndex(index)

            # 设置调试模式
            if debug_open == "1":
                # 如果有调试复选框的话
                if hasattr(self.ui, 'checkBox'):
                    self.ui.checkBox.setChecked(True)
                logger_manager.setup_file_logging(enable_debug=True)

            # 初始化的时候,设置语言选择
            self.setup_language_combo()

            logger_manager.info("用户设置加载完成", "main")

        except Exception as e:
            logger_manager.error(f"加载用户设置失败: {e}", "main")

    def setup_language_combo(self):
        """设置语言选择下拉框"""
        try:
            if not hasattr(self.ui, 'languageComboBox'):
                return

            # 清理现有的项目
            self.ui.languageComboBox.clear()

            # 使用 setItemData 方法
            for lang_code in LANGUAGE_ORDER:
                if lang_code in LANGUAGE_DISPLAY_NAMES:
                    display_name = LANGUAGE_DISPLAY_NAMES[lang_code]  # 显示文本
                    self.ui.languageComboBox.addItem(display_name)  # 添加显示文本
                    # 设置对应的值
                    index = self.ui.languageComboBox.count() - 1
                    self.ui.languageComboBox.setItemData(index, lang_code)

            # 获取当前保存的语言设置
            current_language = settings_manager.get_language_setting("zh_CN")

            # 根据值查找并设置当前选项
            for i in range(self.ui.languageComboBox.count()):
                if self.ui.languageComboBox.itemData(i) == current_language:
                    self.ui.languageComboBox.setCurrentIndex(i)
                    break

            # 设置当前语言到 i18n_manager
            i18n_manager.set_language(current_language)

            logger_manager.info(
                f"语言选择器已设置为: {current_language} (显示名称: {LANGUAGE_DISPLAY_NAMES.get(current_language, current_language)})",
                "main")

        except Exception as e:
            logger_manager.error(f"设置语言选择器失败: {e}", "main")

    @Slot(str)
    def on_language_combo_changed(self, display_text):
        """语言选择改变事件"""
        try:
            # 获取当前选中项的实际值（语言代码）
            current_index = self.ui.languageComboBox.currentIndex()
            language_code = self.ui.languageComboBox.itemData(current_index)

            if language_code:
                # 保存语言设置
                settings_manager.save_language_setting(language_code)

                # 切换语言
                i18n_manager.set_language(language_code)

                logger_manager.info(f"语言已切换为: {language_code} ({display_text})", "main")

        except Exception as e:
            logger_manager.error(f"切换语言失败: {e}", "main")
    def clear_url(self):
        """清空URL输入框"""
        try:
            self.ui.le_url.clear()
            self.ui.progressBar.setValue(0)
            logger_manager.info(_("messages.url_cleared"), "main")

        except Exception as e:
            logger_manager.error(f"清空URL失败: {e}", "main")

    def select_download_path(self):
        """选择下载路径"""
        try:
            current_path = self.ui.le_download_path.text().strip()
            if not current_path:
                current_path = os.path.expanduser("~/Downloads")

            selected_path = QFileDialog.getExistingDirectory(
                self,
                "选择下载路径",
                current_path
            )

            if selected_path:
                self.ui.le_download_path.setText(selected_path)
                # 保存到设置
                self.save_download_path(selected_path)
                logger_manager.info(f"下载路径已设置: {selected_path}", "main")

        except Exception as e:
            logger_manager.error(f"选择下载路径失败: {e}", "main")
            show_error(self, "错误", f"选择下载路径失败: {e}")

    def save_download_path(self, path):
        """保存下载路径到设置"""
        try:
            # 获取当前设置
            last_input_path, last_output_path, debug_open, select_resolution, is_mp4, lange = settings_manager.get_main_info()

            # 保存新的下载路径
            settings_manager.save_main_info(
                last_input_path,
                path,  # 新的下载路径
                debug_open,
                select_resolution,
                is_mp4,
                lange
            )

        except Exception as e:
            logger_manager.error(f"保存下载路径失败: {e}", "main")

    @Slot(dict)
    def update_system_monitor_display(self, monitor_info):
        """更新系统监控显示"""
        try:
            if 'error' in monitor_info:
                logger_manager.error(f"系统监控错误: {monitor_info['error']}", "main")
                return

            # 构建系统监控信息文本
            status_text = f"{_('labels.system_monitor')} | {_('labels.cpu')}: {monitor_info.get('system_cpu', 0):.1f}% | "
            status_text += f"{_('labels.memory')}: {monitor_info.get('process_memory_text', 'N/A')}"

            # 如果有网速信息，添加到显示文本中
            if 'upload_speed' in monitor_info and 'download_speed' in monitor_info:
                status_text += f" | {_('labels.network_speed')}: ↑{monitor_info['upload_speed']} ↓{monitor_info['download_speed']}"

            # 使用QTimer.singleShot确保在UI线程中更新标签文本
            QTimer.singleShot(0, lambda: self.ui.lbl_computer_msg.setText(status_text))

        except Exception as e:
            logger_manager.error(f"更新系统监控显示失败: {e}", "main")
            # 即使出错也要在UI线程中安全更新
            QTimer.singleShot(0, lambda: self.ui.lbl_computer_msg.setText(_("messages.system_monitor_error")))

    @Slot(str)
    def on_language_changed(self, lang_code):
        """处理语言切换"""
        try:
            # 重新设置UI文本
            self.setup_character_art_texts()

            # 更新窗口标题
            self.setWindowTitle(_("app_title"))

            # 如果历史窗口打开，也需要更新
            if self.history_window and not self.history_window.isHidden():
                self.history_window.update_ui_texts()

            logger_manager.info(f"语言已切换到: {i18n_manager.get_supported_languages().get(lang_code, lang_code)}",
                                "main")

        except Exception as e:
            logger_manager.error(f"语言切换失败: {e}", "main")

    def bring_to_front(self):
        """将主窗口置顶显示"""
        try:
            self.raise_()
            self.activateWindow()
            self.setWindowState(
                (self.windowState() & ~Qt.WindowState.WindowMinimized) | Qt.WindowState.WindowActive
            )
            # 在Windows上强制置顶
            self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)
            self.show()
            self.setWindowFlags(self.windowFlags() & ~Qt.WindowType.WindowStaysOnTopHint)
            self.show()
            logger_manager.info("主窗口已置顶", "main")
        except Exception as e:
            logger_manager.error(f"主窗口置顶失败: {e}", "main")

    def show_about(self):
        """显示关于对话框"""
        try:
            about_text = _("dialogs.about_content").format(
                version=_("version"),
                author=_("author")
            )
            show_info(self, _("dialogs.about_title"), about_text)

        except Exception as e:
            logger_manager.error(f"显示关于对话框失败: {e}", "main")


    def show_help(self):
        """显示帮助信息"""
        try:
            help_text = _("dialogs.help_content")
            show_info(self, _("dialogs.help_title"), help_text)

        except Exception as e:
            logger_manager.error(f"显示帮助信息失败: {e}", "main")
            
    # 线程安全de 追加单条日志消息到UI
    @Slot(str)
    def _append_log_message(self, message):
        """追加单条日志消息到UI（线程安全）"""
        if hasattr(self.ui, 'textEdit_debug'):
            self.ui.textEdit_debug.append(message)
            # 自动滚动到底部
            cursor = self.ui.textEdit_debug.textCursor()
            cursor.movePosition(cursor.MoveOperation.End)
            self.ui.textEdit_debug.setTextCursor(cursor)

    # 批量追加日志到UI
    @Slot(list)
    def _append_batch_log_messages(self, messages):
        """批量追加日志消息到UI（线程安全）"""
        if hasattr(self.ui, 'textEdit_debug') and messages:
            for message in messages:
                self.ui.textEdit_debug.append(message)
            # 自动滚动到底部
            cursor = self.ui.textEdit_debug.textCursor()
            cursor.movePosition(cursor.MoveOperation.End)
            self.ui.textEdit_debug.setTextCursor(cursor)

if __name__ == "__main__":
    # 调试本窗口的时候使用, 这个部分通常不会被执行，因为主窗口是从启动界面启动的
    app = QApplication(sys.argv)

    # 设置中文语言环境
    from PySide6.QtCore import QLocale, QTranslator, QLibraryInfo

    locale = QLocale(QLocale.Language.Chinese, QLocale.Country.China)
    QLocale.setDefault(locale)

    translator = QTranslator()
    qt_translations_path = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath)
    if translator.load(locale, "qtbase", "_", qt_translations_path):
        app.installTranslator(translator)
    else:
        if translator.load(locale, "qt", "_", qt_translations_path):
            app.installTranslator(translator)

    # 注册全局异常处理器
    exception_handler = GlobalExceptionHandler()
    sys.excepthook = exception_handler.handle_exception

    try:
        # 创建并显示主窗口
        main_window = MainWindow()
        main_window.show()

        # 进入事件循环
        sys.exit(app.exec())
    except Exception as e:
        import traceback

        logger_manager.error(f"应用程序启动失败: {e}", "main")
        logger_manager.error(f"堆栈跟踪: {traceback.format_exc()}", "main")
        sys.exit(1)